/*
 * @lc app=leetcode.cn id=25 lang=javascript
 *
 * [25] K 个一组翻转链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
function reverse (prev, cur) {
    if (!cur) return prev;
    const tem = cur.next;
    cur.next = prev;
    return reverse(cur, tem);
}
var reverseKGroup = function(head, k) {
   if (!head) return head;
   const hair = new ListNode(-1, head);
   let prev = hair;
   while(head) {
       let tail = prev;
       for (let i = 0; i < k; i++) {
           tail = tail.next;
           if (!tail) {
               return hair.next;
           }
       }
       const leftNode = prev.next;
       const nex = tail.next;
       tail.next = null;
       prev.next = null;
       reverse(null, leftNode);
       prev.next = tail;
       leftNode.next = nex;
       head = nex;
       prev = leftNode;
   }
   return hair.next;
};
// @lc code=end

